//封装购物车模块
import { defineStore } from "pinia";
import { ref } from 'vue'
import { computed } from 'vue';
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'
export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  //1.定义state---cartList
  const cartList = ref([])
  //获取最新购物车列表数据action
  const updateNewList=async()=>{
    // 2.调用获取购物车列表接口
    const res = await findNewCartListAPI()
    // 3.用接口购物车列表覆盖本地购物车列表
    cartList.value = res.result
  }
  //2.定义action----addCart
  const addCart = async (goods) => {
    // 解构赋值
    const { skuId, count } = goods
    if (isLogin.value) {
      //添加接口购物车操作
      // 1.调用加入购物车接口
      await insertCartAPI({ skuId, count })
     updateNewList()
    } else {
      //添加本地购物车操作
      //已添加过----count+1
      //没有添加过-----直接push
      //思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，岛国到了就是添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        // 找到了，之前添加过
        item.count++
      } else {
        //没找到
        cartList.value.push(goods)
      }
    }
  }
  const delCart = async(skuId) => {
    if (isLogin.value) {
       await delCartAPI([skuId])
      updateNewList()
    } else {
      //思路：
      // 1.找到要删除项的下标志，然后利用splice删除
      // 2.使用数组的过滤方法---filter
      const idx = cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(idx, 1)
      // cartList.value = cartList.value.filter((item)=>skuId !=item.skuId)
    }

  }
  //清除购物车
  const clearCart=()=>{
    cartList.value=[]
  }
  // 单选功能
  const singleCheck = (skuId, selected) => {
    //通过skuId找到要修改的哪一项，然后把他的selected修改
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }
  // 是否全选
  const isAll = computed(() => cartList.value.every((item) => item.selected))
  //全选功能
  const allCheck = (selected) => {
    //把cartList的每一项都设置为selected，实现全选，全不选
    cartList.value.forEach((item) => item.selected = selected)
  }
  //计算属性
  // 1.总的数量 所有项的count之和
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  // 总价 所有项的count*price之和
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  //选中的数量
  const selectedCount = computed(() => cartList.value.filter((item) => item.selected)
    .reduce((a, c) => a + c.count, 0))
  //选中购物车商品的总价格
  const selectedPrice = computed(() => cartList.value.filter((item) => item.selected)
    .reduce((a, c) => a + c.count * c.price, 0))
  return {
    cartList,
    addCart,
    delCart,
    allPrice,
    allCount,
    singleCheck,
    isAll,
    allCheck,
    selectedCount,
    selectedPrice,
    clearCart,
    updateNewList
  }
},
  //加入本地缓存
  {
    persist: true,
  }
)